# -*- coding:utf-8 -*-

# 风格系统的通用DatasetMoldBase基类

from datakeeper.dataset_mold import *
from datakeeper.utils import *
from datasets.utils.data import *
from datasets.utils.plot import *
from datasets.utils.kmz import *
import pandas.json as _json
from weblib.django.setting import get_setting


class FG_DatasetMoldBase(DatasetMoldBase):
    uri_parser = None
    allow_RY_download_json = False
    zh_subset_d = {}
    zh_varname_d = {}

    @protect_hack
    def topset_get_file(self, uri, dest, request=None, *args, **kwargs):
        try:
            uri_info = self.uri_parser(uri)
            subset = self.uri_subsets.get(uri_info['subset'], None)
            if subset is None:
                raise ValueError("No such subset: %s" % uri_info['subset'])

            getres = subset.get_file(uri, dest, request=request, *args, **kwargs)
            return getres
        except Exception as e:
            raise GetFileError(u'[%s] %s' % (type(e), unicode(e)))


    def RY_get_file(self, uri, dest, request=None, *args, **kwargs):
        format = kwargs.pop('format', 'figinfo')

        if format == 'figure':
            kwargs['datatype'] = 'dataunit'
        elif format == 'figinfo':
            kwargs['datatype'] = 'figinfo'
        elif format == 'rect_figure':
            kwargs['datatype'] = 'dataunit'
        elif format == 'kmz':
            kwargs['datatype'] = 'dataunit'
        elif format == 'json' and self.allow_RY_download_json:
            kwargs['datatype'] = 'dataunit'
        else:
            raise GetFileError("Format %s not allowed" % format)

        datares = self.get_data(uri, request=request, *args, **kwargs)

        info = {}
        if format == 'figure':
            dataobj = datares['data']
            data = dataobj['values']
            LON = dataobj['lon']
            LAT = dataobj['lat']

            vmin = kwargs.get('vmin', dataobj['suggest_range'][0])
            vmax = kwargs.get('vmax', dataobj['suggest_range'][1])
            plot_lonlat_data(LON, LAT, data,
                             fig_fname=dest,
                             target='map',
                             projection=kwargs.get('projection', 'merc'),
                             pitem=kwargs.get('pitem', None),
                             vmin=vmin, vmax=vmax,
                             cmap=kwargs.get('cmap', 'jet'),
                             level_n=kwargs.get('level_n', 64),
                             xpixels=kwargs.get('xpixels', None),
                             title=uri, units=''
                             )

            info['filetype'] = 'figure'
            info['format'] = 'png'
        elif format in ['rect_figure', 'kmz']:
            dataobj = datares['data']
            data = dataobj['values']
            LON = dataobj['lon']
            LAT = dataobj['lat']

            vmin = kwargs.get('vmin', dataobj['suggest_range'][0])
            vmax = kwargs.get('vmax', dataobj['suggest_range'][1])
            pitem = kwargs.get('pitem', None)

            units = dataobj.get('units')
            dataset = kwargs.get('uri_info').get('dataset')
            # dataset_zh = fgwrf_zh_dataset_d.get(dataset)
            dataset_zh = self.zh_name
            subset = kwargs.get('uri_info').get('subset')
            subset_zh = self.zh_subset_d.get(subset)
            varname = kwargs.get('uri_info').get('varname')
            varname_zh = self.zh_varname_d.get(varname)
            units = dataobj.get('units')
            uri_zh = uri
            for name, zh_name in zip([dataset, subset, varname], [dataset_zh, subset_zh, varname_zh]):
                uri_zh = uri_zh.replace(name, zh_name)
            if format == 'rect_figure':
                plot_lonlat_data(LON, LAT, data,
                                 fig_fname=dest,
                                 target='fig',
                                 projection=kwargs.get('projection', 'merc'),
                                 pitem=pitem,
                                 vmin=vmin, vmax=vmax,
                                 cmap=kwargs.get('cmap', 'jet'),
                                 level_n=kwargs.get('level_n', 64),
                                 xpixels=kwargs.get('xpixels', None),
                                 title=uri_zh, units=units,
                                 colorbar_title=varname_zh
                                 )

                info['filetype'] = 'rect_figure'
                info['format'] = 'png'
            elif format == 'kmz':
                src_img = kmz_manager.get(gen_uuid8(), when_not_exist=('create',))
                color_bar_img = kmz_manager.get(gen_uuid8(), when_not_exist=('create'),)

                plot_res = plot_lonlat_data(LON, LAT, data,
                                            fig_fname=src_img.filepath,
                                            colorbar_fname=color_bar_img.filepath,
                                            target='map',
                                            projection=kwargs.get('projection', 'cyl'),
                                            pitem=pitem,
                                            vmin=vmin, vmax=vmax,
                                            cmap=kwargs.get('cmap', 'jet'),
                                            level_n=kwargs.get('level_n', 64),
                                            xpixels=kwargs.get('xpixels', None),
                                            pixel_per_grid=16,
                                            title='', units=units,
                                            colorbar_title=varname_zh
                                            )
                # TODO
                logo_img_path = get_setting('KMZ_LOGO', None)
                gen_src_img_kmz(dest, plot_res['lon1'], plot_res['lat1'], plot_res['lon2'], plot_res['lat2'],
                                src_img_path=src_img.filepath,
                                colorbar_img_path=color_bar_img.filepath,
                                logo_img_path=logo_img_path,
                                folder_name=uri_zh)
                info['filetype'] = 'kmz'
                info['format'] = 'kmz'
        elif format in ['figinfo', 'json']:
            with open(dest, 'w') as outf:
                outf.write(_json.dumps(datares, date_unit='s', double_precision=4))
            info['filetype'] = kwargs['datatype']
            info['format'] = 'json'
        info['status'] = 'OK'
        return info
